import axios from 'axios'
import { useMessage } from 'naive-ui';
import { useGlobSetting } from '@/hooks/setting';
import { storage } from './Storage';
import { ACCESS_TOKEN, refreshTokena } from '@/store/mutation-types';
import { useRouter } from 'vue-router';
import { info } from 'console';

import { createStorage } from '@/utils/Storage';

const router = useRouter();
const message = useMessage();

const Storage = createStorage({ storage: localStorage });
const bsinRequest = axios.create({
  timeout: 50000
})

// 请求拦截
bsinRequest.interceptors.request.use(config => {

  // 获取baseURL
  const baseURL = useGlobSetting().apiUrl

  // const rechargeBaseURL = useGlobSetting().rechargeUrl
  // console.log(rechargeBaseURL);
  // if (config.data.sysHead.stdIntfcInd !== "execute")
   config.url = baseURL
  // else {
    // config.url = rechargeBaseURL
  // }

  // 每一个请求都携带token
  let refreshToken = storage.get(refreshTokena)
  let token = storage.get(ACCESS_TOKEN)
  config.headers.token = token// token
  config.headers.refreshToken = refreshToken// refreshToken

  // 判断是否为登录请求并且判断请求是否携带token / refreshToken
  if (config.data.sysHead.stdIntfcInd !== "login" && config.data.sysHead.stdIntfcInd !== "getValidatePicture" && config.data.sysHead.stdIntfcInd !== "reset") {
    if (!token) {
      if (!refreshToken) {
        message.info('权限未获取请重新登陆')
        location.reload()
        router.replace('/login');
      }
    }
  }

  // 系统报文
  const sysHead = {
    srcConsmSysInd: "DAMMER",
    stdIntfcVerNo: "1.0.0",
    ...config.data.sysHead
  }

  let custNoValue = Storage.get('custNo');
  // 本地报文
  const localHead = {
    custNo: custNoValue,
  }

  if (config.params) {
    Object.assign(config.params, { orgId: token })
  }
  if (config.method === 'post' && config.headers.serialize) {
    delete config.data.serialize
  }

  // 组装请求体
  const data = {
    sysHead,
    localHead,
    body: {
      ...config?.data?.body,
    },
  }

  // http
  const array = {
    ...config,
    data
  }
console.log(array);

  return {
    ...array
  }

});

// 响应拦截
bsinRequest.interceptors.response.use(
  res => {
    if (res.data.sysHead.retCd === "NDAMMC-B-100018") {
      localStorage.clear()
      location.reload()
      router.push('/login')
    }
    if (res.data.sysHead.retCd === "NDAMMC-B-100011") {
      localStorage.clear()
      location.reload()
      router.push('/login')
    }
    if (res.data.sysHead.retCd !== "000000") {// 请求失败
      return res
    }
    if (res.data.sysHead.retCd === "000000") {// 请求成功
      return res
    }
  }
)
export default bsinRequest;